import { App } from './app';
import Util from './util';
import { Page } from './page';
import './dx-ext';

let crudGridInstance=$(".data-grid").dxDataGrid("instance")
App.registerRoute({
	name: 'data/order', 
	onLoad: (context, $container) => {

		let origin=context.params.data;

		let orderdata="",title,text,series,basic='',columns;



		if(origin == 'chart-order'){

		orderdata= new DevExpress.data.DataSource({
        store: $.crudStore(API('chart-order'))
      });

		title = '订单数据';

		text = '订单总金额';

		basic = '订单总量';

		series = [
	            { valueField: "total", name: "订单总量", type: 'bar',axis:'basic' },
	            { valueField: "total_fee", name: "订单总金额", axis: 'sale' }
	        ];

	    columns =  [{
				dataField:'date',
				caption: '日期'
			}, {
				dataField:'total',
				caption: '全部订单量'
			}, {
				dataField:'total_fee',
				caption: '订单总金额'
			}, {
				dataField:'general_quantity',
				caption: '普通订单成交量'
			}, {
				dataField:'gift_quantity',
				caption: '赠礼订单成交量'
			}, {
				dataField:'qr_general_quantity',
				caption: '二维码来源普通订单'
			}, {
				dataField:'qr_gift_quantity',
				caption: '二维码来源赠礼订单'
			}];


		}else 
		if(origin == "chart-visit"){


		orderdata= new DevExpress.data.DataSource({
        store: $.crudStore(API('chart-visit'))
      });

		title = '浏览数据';

		text = '葡萄酒浏览量';

		basic = '二维码来源浏览量';

		series = [
		 		{ valueField: "qr_pv", name: "二维码来源浏览量", axis: 'sale' },
	            { valueField: "pv", name: "葡萄酒浏览量", type: 'bar' ,axis:'basic'}
	           
	        ]

	    columns = [{
				dataField:'date',
				caption: '日期'
			}, {
				dataField:'total',
				caption: '葡萄酒详情页总浏览量'
			}, {
				dataField:'qr_pv',
				caption: '二维码来源浏览量'
			}, {
				dataField:'qr_uv',
				caption: '二维码来源浏览人数'
			}, {
				dataField:'pv',
				caption: '普通来源浏览量'
			}, {
				dataField:'uv',
				caption: '普通来源浏览人数'
			}]

		}else{


		orderdata = new DevExpress.data.DataSource({
        store: $.crudStore(API('chart-new'))
      });

		title = '新增数据';

		text = '新增用户';

		series = [
	          
	            { valueField: "count", name: "新增用户", axis: 'sale' }
	        ]

	    columns =  [{
				dataField:'date',
				caption: '日期'
			}, {
				dataField:'count',
				caption: '新增用户'
			}, {
				dataField:'qrcode',
				caption: '二维码来源新增'
			}, {
				dataField:'other',
				caption: '其他来源新增'
			}]
		}


		let page = new Page($container);

		page.crudLayout({title:title});

		page.content.html(`
			<div class="panel panel-default">
			    <div class="panel-heading font-bold">
			      查看数据
			    </div>
			    <div class="panel-body">
			    	<div class="toolbar1"></div>
			    	<div class="data-chart"></div>
			    	<div class="toolbar2"></div>
			    	<div class="data-grid"></div>
			    </div>
		  	</div>
		`);



		let filterExpr={start:'',end:'',type:''},applyFilterExpr=()=>{
			var da = App.crudChartInstance().option('dataSource'),
			    ds = $('.data-grid').dxDataGrid('instance').option('dataSource');
			orderdata = new DevExpress.data.DataSource({
        store: $.crudStore(API(`${origin}?start=${filterExpr.start}&end=${filterExpr.end}&type=${filterExpr.type}`))
      });
			INSERT()
		}

		let items = [{
				location:'after',
				widget:'dxDateBox',
				options: {
					displayFormat: "yyyy-MM-dd",
					dateSerializationFormat: 'yyyy-MM-dd',
					placeholder: '开始时间',
					onValueChanged:function(e){
						filterExpr.start = e.value;
						applyFilterExpr()
					
					}
				}
			}, {
				location:'after',
				widget:'dxDateBox',
				options: {
					displayFormat: "yyyy-MM-dd",
					dateSerializationFormat: 'yyyy-MM-dd',
					placeholder: '结束时间',
					onValueChanged:function(e){
					filterExpr.end = e.value;
						applyFilterExpr()
					}
				}
			}];

			if(origin == 'chart-new'){
			items.push({
				location:'before',
				widget:'dxSelectBox',
				options:{
					placeholder:'请选择类型',
					dataSource:[{name:'浏览',type:'view'},{name:'订单',type:'order'}],
					displayExpr:'name',
					valueExpr:'type',
					value:'view',
					onValueChanged:function(e){
						console.log(e)
						filterExpr.type=e.value;
						applyFilterExpr()
					}
				}
			})
	    
	    }

		page.content.find('.toolbar1').dxToolbar({
			items: items
		});

		

		
function INSERT(){ 
		page.content.find(".data-chart").dxChart({
	        palette: "violet",
	        dataSource: orderdata,
	        rotated:false,
	        commonSeriesSettings: {
	            argumentField: "date",
	            type: 'line',
	            bar: {
		            barWidth: 20,
		            barPadding: 0.5,
		            barGroupPadding: 0.5
	            }
	        },
	        margin: {
	            bottom: 20
	        },
	        valueAxis: [{
	        	// name:'basic',
	        	// position:'left',
	            grid: {
	                visible: true
	            },
	            // title:{
	            //     text:basic
	            //     }
	        }, {
	            name: "sale",
	            position: "right",
	            grid: {
	                visible: true
	            },
	            title: {
	                text: text
	            }
	        }],
	        series: series,
	        legend: {
	            verticalAlignment: "top",
	            horizontalAlignment: "right",
	            itemTextPosition: "right",
	            orientation:'vertical'
	        },
	        tooltip: {
	            enabled: true,
	            customizeTooltip: function (arg) {
	                return {
	                    html:`<div><div class='tooltip-header'>${arg.argument}</div>${arg.seriesName}:${arg.valueText}</div>`
	                };
	            }
	        }
	    });


	    page.content.find('.toolbar2').dxToolbar({
			items: [{
				location:'after',
				widget:'dxButton',
				options: {
					text: '导出',
					onClick: function(e){
					
					window.location=API(`${origin}?export=true&start=${filterExpr.start}&end=${filterExpr.end}&type=${filterExpr.type}`)
					}
				}
			}]
		});

		page.content.find('.data-grid').dxDataGrid({
			dataSource:orderdata,
			columns:columns
		});
	}

	INSERT()
	}
});

App.registerRoute({
	name:'manage/gift',
	onLoad:function(context,$container){
		let page=new Page($container);
		let columns =[],title,tooltip,dataSource;
		let origin=context.params.data;

   		if(origin){
   			columns = [{
			caption:'id',
			dataField:'id'
		},{
			caption:'类型',
			dataField:'category',
			cellTemplate:function($c,d){
				let text = '';
				switch(d.value){
					case 'general':text='普通';break;
					case 'product':text='指定商品';break;
					case 'importer':text='指定进口商';break;
					case 'dealer':text='指定经销商'
				};
				$c.text(text)
				
			}
		},{
			caption:'进口商/商品',
			dataField:'importerName',
			cellTemplate:function($c,d){
				let text = d.data.importerName?d.data.importerName:d.data.productName
				$c.text(text)
			}
		},{
			caption:'满减类型',
			dataField:'couponName'

		}]

		title = '优惠券管理';

		tooltip = '优惠券类型管理列表';

		dataSource = $.crudStore(API('restful?_model=sys-coupon-category'))

   		}else{
   			columns = [{
   				caption:"id",
   				dataField:'id'
   			},{
   				caption:'优惠券名称',
   				dataField:'coupon_name'
   			},{
   				caption:'活动名称',
   				dataField:'name'
   			},{
   				caption:'领取开始时间',
   				dataField:'can_get_start'
   			},{
   				caption:'领取结束时间',
   				dataField:'can_get_end'
   			},{
   				caption:'使用量',
   				dataField:'used'
   			},{
   				caption:'领取量',
   				dataField:'get'
   			},{
   				caption:'库存剩余量',
   				dataField:'sku',
   				cellTemplate:function(c,d){
   					
   					let $datagird = page.content.find('.data-grid').dxDataGrid('instance').option('dataSource');

   					$('<a>').text(d.value).css('text-decoration','underline').click(function(){
   						let num = prompt('请输入要修改的数值');
   					if(num) { 
   					d.data.sku=num
   					$.crudStore(API('restful?_model=sys-coupon')).update(d.data.id,d.data).then(res=>{
   						DevExpress.ui.notify({message:'修改成功'},'success',1500)
   						$datagird.load()
   					}).fail(function(){
   						DevExpress.ui.notify({message:'错误'},'warning',1500)
   					}) }
   					}).appendTo(c)
   				}
   			}];

   			title = '优惠券使用';

   			tooltip = '优惠券活动使用列表';

   			dataSource = $.crudStore(API('restful?_model=sys-coupon'))
   		}
		

		page.crudLayout({title:title});
		page.content.html(`<div class="panel panel-default">
			    <div class="panel-heading font-bold">
			      ${tooltip}
			    </div>
			    <div class="panel-body">
			    	<div class="toolbar1"></div>
			    	<div class="data-grid"></div>
			    </div>
		  	</div>`);

		page.content.find('.toolbar1').dxToolbar({
			items:[{
				location:'before',
				widget:'dxButton',
				options:{
					text:'增加',
					onClick:function(e){
						newData()
					}
				}
			}]
		});



		 page.content.find('.data-grid').dxDataGrid({
			dataSource:new DevExpress.data.DataSource({
				store:dataSource
			}), 
			columns:columns
		})


		function newData(){
			let newtitle,new_data,new_items;
			var now = new Date();
			if(origin){
			 newtitle = '新建优惠券';
			 new_data = new DevExpress.data.CustomStore({
				store:$.crudStore(API('restful?_model=use-coupon'))
			});

			 new_items = [{
				label:{text:'优惠券类型'},
				editorType:'dxSelectBox',
				dataField:'category',
				editorOptions:{
					dataSource:[{name:'普通',type:'general'},{name:'指定商品',type:'product'},{name:'指定进口商',type:'importer'}],
					displayExpr:'name',
					valueExpr:'type',
					onValueChanged(e){
						let $container = $('.formData').find(".new_tool_data").dxForm('instance');
						$container.option('formData.category',e.value);
						if(e.value == 'general'){
						 	$container.getEditor('importer_id').element().closest('.dx-field-item').addClass('hidden')
							$container.getEditor('dealer_id').element().closest('.dx-field-item').addClass('hidden');
							$container.option({'formData.importer_id':null,'formData.dealer_id':null});

						}else if(e.value == 'product'){
							$container.getEditor('importer_id').element().closest('.dx-field-item').removeClass('hidden')
							$container.getEditor('dealer_id').element().closest('.dx-field-item').addClass('hidden');
							$container.option('formData.dealer_id',null)
						}else {
							$container.getEditor('dealer_id').element().closest('.dx-field-item').removeClass('hidden')
							$container.getEditor('importer_id').element().closest('.dx-field-item').addClass('hidden')
							$container.option('formData.importer_id',null)
						}
						
					}
				}
			},
			{
				dataField:'importer_id',
				cssClass:'hidden',
				label:{text:'指定商品'},
				editorType:'dxSelectBox',
				editorOptions:{
					dataSource:$.crudStore(API('restful?_model=wine-product')),
					valueExpr:'id',
					displayExpr:'chname',
					placeholder:'指定商品',
					onValueChanged:function(ev){
					let $container = $('.formData').find(".new_tool_data")
					$container.dxForm('instance').option('formData.product_id',ev.value);

							}
				}
			},{
				dataField:'dealer_id',
				cssClass:'hidden',
				label:{text:'指定进口商'},
				editorType:'dxSelectBox',
				editorOptions:{
					dataSource:$.crudStore(API('restful?_model=sys-importer')),
					placeholder:'指定进口商',
					valueExpr:'id',
					displayExpr:'name',
					onValueChanged:function(ev){
					let $container = $('.formData').find(".new_tool_data")
					$container.dxForm('instance').option('formData.importer_id',ev.value);	
							}
				}
			},
			{
				label:{text:'满减类型'},
				editorType:'dxSelectBox',
				editorOptions:{
					dataSource:[{name:'直减',type:'direct'},{name:'满减',type:'full'}],
					valueExpr:'type',
					displayExpr:'name',
					onValueChanged:function(e){
					let $container = $('.formData').find(".new_tool_data").dxForm('instance');	

					$container.option('formData.loseType',e.value)

					if(e.value == 'direct'){
							$container.getEditor('full_amount').element().closest('.dx-field-item').addClass('hidden')
						// $container.itemOption('on_select_amount','items',[{label:{text:'直减'},dataField:'amount'}]);
					}else{
						$container.getEditor('full_amount').element().closest('.dx-field-item').removeClass('hidden')
					    // $container.itemOption('on_select_amount',"items",[{label:{text:'满'},dataField:'full_amount'},{label:{text:'减'},dataField:'amount'}])
					}
					
					
					}
				}
			},{
				itemType:'group',
				colCount:2,
				caption:'on_select_amount',
				items:[{
					label:{text:'满'},
					dataField:'full_amount'
				},{
					label:{text:'减'},
					dataField:'amount'
				}]
				
			}]
			}else{
				newtitle = '新建优惠券活动';
				new_data = new DevExpress.data.CustomStore({
					store:$.crudStore(API('restful?_model=sys-coupon'))
				});

				new_items=[{
					label:{text:'活动名称'},
					dataField:'name'
				},{
					label:{text:'通用类型'},
					dataField:'coupon_category_id',
					editorType:'dxSelectBox',
					editorOptions:{
						dataSource:$.crudStore(API('restful?_model=sys-coupon-category')),
						displayExpr:'couponName',
						valueExpr:'id',
						onValueChanged:function(e){
							let $container = $('.formData').find('.new_tool_data').dxForm('instance');
							$container.option('formData.coupon_category_id',e.value)
						}
					}
				},{
					label:{text:'领取有效期'},
					itemType:'group',
					colCount:2,
					items:[{
						dataField:'can_get_start',
						label:{text:'自'},
						editorType:'dxDateBox',
						editorOptions:{
							type: "date",
							displayFormat: 'yyyy-MM-dd',
							dateSerializationFormat: "yyyy-MM-dd",
							editorOptions: {
							displayFormat: 'yyyy-MM-dd',
							dateSerializationFormat: 'yyyy-MM-dd'
					}
						}
					},{
						label:{text:'至'},
						dataField:'can_get_end',
						editorType:'dxDateBox',
						editorOptions:{
							type: "date",
							displayFormat: 'yyyy-MM-dd',
							dateSerializationFormat: "yyyy-MM-dd",
							editorOptions: {
							displayFormat: 'yyyy-MM-dd',
							dateSerializationFormat: 'yyyy-MM-dd'
					}
						}
					}]
				},{
					label:{text:'使用有效期'},
					itemType:'group',
					colCount:2,
					items:[
					{	editorType:'dxRadioGroup',
						editorOptions:{
							layout: "horizontal",
							items:[{text:'固定日期',value:'yes'},{text:'浮动日期',value:'no'}],
							value:'yes',
							valueExpr:'value',
							onValueChanged:function(e){
								let value = e.value=='yes'?'no':'yes'
							let $container = $('.formData').find('.new_tool_data').dxForm('instance');
							$container.option('formData.enable_use_date',e.value);
							$container.option('formData.enable_use_days',value);
							if(e.value ==  'yes'){
								$container.getEditor('can_use_start').element().closest(".dx-field-item").removeClass('hidden');
								$container.getEditor('can_use_end').element().closest(".dx-field-item").removeClass('hidden');
								$container.getEditor('can_use_days').element().closest(".dx-field-item").addClass('hidden');
								
							}else{
								$container.getEditor('can_use_start').element().closest(".dx-field-item").addClass('hidden');
								$container.getEditor('can_use_end').element().closest(".dx-field-item").addClass('hidden');
								$container.getEditor('can_use_days').element().closest(".dx-field-item").removeClass('hidden');
								
							}

							}
						}
					},
					{
							editorType:'dxTextBox',
							cssClass:'hidden'
					},
					{
						dataField:'can_use_start',
						label:{text:'自'},
						editorType:'dxDateBox',
						editorOptions:{
							type: "date",
							displayFormat: 'yyyy-MM-dd',
							dateSerializationFormat: "yyyy-MM-dd",
							editorOptions: {
							displayFormat: 'yyyy-MM-dd',
							dateSerializationFormat: 'yyyy-MM-dd'
					}
						}
					},{
						dataField:'can_use_end',
						label:{text:'至'},
						editorType:'dxDateBox',
						editorOptions:{
							type: "date",
							displayFormat: 'yyyy-MM-dd',
							dateSerializationFormat: "yyyy-MM-dd",
							editorOptions: {
							displayFormat: 'yyyy-MM-dd',
							dateSerializationFormat: 'yyyy-MM-dd'
					}
						}
					},{
						label:{text:'自领取日期起'},
						dataField:'can_use_days',
						cssClass:'hidden'
					}
					]
				},{
					label:{text:'使用条件'},
					editorType:'dxSelectBox',
					editorOptions:{
						dataSource:[{name:'新用户',value:'new'},{name:'老用户',value:'old'},{name:'新老用户',value:'all'}],
						displayExpr:"name",
						valueExpr:'value',
						onValueChanged:function(e){
							let $container = $('.formData').find('.new_tool_data').dxForm('instance');
							$container.option('formData.condition',e.value);

						}
					}
				},{
					label:{text:'库存量'},
					dataField:'sku'
				}]

			}
			

			$("#popups").html('<div>');
			
			$("<div/>").appendTo($("#popups")).dxPopup({
					width:800,
					height:600,
					visible:true,
					title:newtitle,
					contentTemplate: function(contentElement) {
					return '<div class="formData"><div class="new_tool_data"></div><div class="toolbar2" style="margin:30px auto;display:block"></div></div>'
					},
					onContentReady:function(e){
						let $content = e.component.content();

						$content.find('.new_tool_data').dxForm({
						dataSource:new_data,
            			validationGroup: "crud",
            			items:new_items
						});

						$content.find('.toolbar2').dxButton({
							type:'success',
							text:'创建',
							onClick:function(){
								let data = $('.formData').find('.new_tool_data').dxForm('instance').option('formData');
						console.log(data);
						let route = ''
						if(origin){
							route = 'restful?_model=sys-coupon-category'
						}else{
							route = 'restful?_model=sys-coupon';
							data.enable_use_date=data.enable_use_date?data.enable_use_date:'yes';
							data.enable_use_days=data.enable_use_days?data.enable_use_days:'no'
						};

						$.ajax({url:API(route),method:'post',data:data}).always(function(resp){
							console.log(resp)
							if(resp.status == 'success'){
								DevExpress.ui.notify({message:'创建成功'},'success',1500);
							$("#popups").find('div').remove();
								 page.content.find('.data-grid').dxDataGrid('instance').option('dataSource').reload()
							}else{
								DevExpress.ui.notify({message:function(){

									let text = "提示:"+resp.responseJSON.message;
									return text
								}},'warning',1500)
							}
								})
							
							}
						})
					}
				})
		}
	}
})

App.registerRoute({
	name:'modify_pwd',
	onLoad:function(content,$container){
		let page = new Page($container);
		page.content.html(`<div class="panel panel-default">
		    <div class="panel-heading font-bold">
			     修改密码
			    </div>
			    <div class="crud-container crud-reset row">
			      	<div class="col-md-12">
			    		<div class="data-grid" style='padding:50px;border:0'></div>
			    	</div>
			      	<div class="col-md-12">
			     		<div class="toolbar2" style='padding:0 130px'></div>
			      	</div>
			    </div>

		  	</div>`);

		page.content.find('.data-grid').dxForm({
		readOnly:false,
		showColonAfterLabel:true,
		showValidationSummary:false,
		colCount:1,
		items:[{
			dataField:'old_password',
			label:{text:'原密码'},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		},{
			dataField:'password',
			label:{text:'新密码'},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		},{
			dataField:'password_confirmation',
			label:{text:"确认密码"},
			editorOptions: {
				mode: 'password'
			},
			validationRules: [{
				type: "required"
			}]
		}]
		})

		page.content.find('.toolbar2').dxToolbar({
			items:[
				{	
					location:'before',
					widget:"dxButton",
					options:{
						text:'确认修改',
						type:'success',
						onClick:function(){
							let data = page.content.find('.data-grid').dxForm('instance').option('formData');
							$.ajax({
								url:API('auth/change-password'),
								headers:{Authorization: "bearer " + localStorage.accessToken},
								method:'post',
								data:data,
								success:function(res){
								
									DevExpress.ui.notify({message:'修改成功'},'success',1500);
									setTimeout(function(){window.location.href = 'login.html'},1500)
								},
								error:function(err){
									DevExpress.ui.notify({message:function(){
										let text = '提示 ：' +err.responseJSON.message;
										return text
									}},'warning',2000);

								}
							})
						}
					}
				}
			]
		})
	}

})




App.registerRoute({
	name:"activity",
	onLoad:function(context,$container){
		let page=new Page($container);
		let origin=context.params.id;
		let origin_name = '查看活动'
		if(origin == 'NEW'){
			origin_name = '新建活动'
		};
console.log(1);
		page.crudLayout({title:"活动"});
			page.content.html(`<div class="panel panel-default">
		    <div class="panel-heading font-bold">
			      ${origin_name}
			    </div>
			    <div class="panel-body" >
			    	<form>
			    	<div class="data-grid"  style='padding:10px'></div>
			    	<div class="toolbar1" style='float:right'></div>
			    	</form>
			    </div>
		  	</div>`);

//葡萄酒
		let drink_list=[{
			label:{text:'葡萄酒'},
			dataField:"products",
			editorType: 'dxTagBox',
              editorOptions: {
                deferRendering: false,
                dataSource: $.crudStore(API("simplelist?_model=wine-product")),
                searchEnabled: true,
                valueExpr: 'id',
                displayExpr: 'chname'
              }
		}]
//文章
		let detail1=[{label:{text:'活动详情'},
			dataField:"detail_text",
			editorType:'dxEditor'}],
//海报
			detail2=[{label:{text:'活动详情'},
			dataField:"detail_pic",
			editorType:'imagesdetail',
			editorOptions:{
				imageWidth:750,
				imageHeight:1200
			}}],

//时间	
		watch_time =new Date(),
		DATE = watch_time.getFullYear()+'-'+(watch_time.getMonth()+1)+'-'+watch_time.getDate(),
		newtime = new Date(DATE),
		edit_option ={
			value:newtime,
			type: "datetime",
			displayFormat: 'yyyy-MM-dd HH:mm:ss',
			dateSerializationFormat: "yyyy-MM-dd HH:mm:ss"
		}

	if(origin != 'NEW'){
		edit_option ={
			type: "datetime",
			displayFormat: 'yyyy-MM-dd HH:mm:ss',
			dateSerializationFormat: "yyyy-MM-dd HH:mm:ss"
		}
	}

	let	apply_time = [{
			dataField:'start_time',
			label:{text:'活动时间'},
			editorType:'dxDateBox',
			editorOptions:edit_option
		},{
			dataField:"end_time",
			label:{text:'至'},
			editorType:'dxDateBox',
			editorOptions:edit_option
		},{
			label:{text:'报名截止'},
			dataField:"deadline",
			editorType:'dxDateBox',
			editorOptions:{
				type: "date",
				displayFormat: 'yyyy-MM-dd',
				dateSerializationFormat: "yyyy-MM-dd"
			}
		}]

//公用
		let aplay =[{
			label:{text:'是否需要分享'},
			dataField:"need_share",
			editorType:'dxRadioGroup',
			validationRules: [{
                type: "required"
              }],
			editorOptions:{
				layout: "horizontal",
				displayExpr:'text',
				valueExpr:'value',
				dataSource:[{
					text:'不需要',
					value:0
				},{
					text:'需要',
					value:1
				}]
			}
		},{
			label:{text:'用户分享规则'},
			dataField:"share_rule",
			editorType:'dxNumberBox'
		},{
			itemType:"group",
			colCount:2,
			items:apply_time
		}]
		
//收费

		let item1 = [{
			label:{text:'活动讲师'},
			dataField:"lecturer_id"
		},{
			itemType:'group',
			colCount:1,
			items:drink_list
		},{
			label:{text:'参与人员限制'},
			dataField:"participate_limit"
		},{
			itemType:'group',
			colCount:1,
			items:aplay
		},{
			itemType:"group",
			colCount:2,
			items:[{
				label:{text:'活动类型'},
				dataField:"cost_type",
				editorType:'dxSelectBox',
				editorOptions:{
					displayExpr:"text",
					valueExpr:"value",
					dataSource:[{
						text:'一人独享',
						value:1
					},{
						text:'二人同行',
						value:2
					},{
						text:'三人结伴',
						value:3
					}]
				}
		},{
			label:{text:'费用'},
			dataField:"cost"
		}]
			
		}]


//免费		
		let item2 =[{
			itemType:'group',
			colCount:1,
			items:drink_list
		},{
			label:{text:'活动名额'},
			dataField:"participate_limit",
			editorType:'dxNumberBox'
		},{
			itemType:'group',
			colCount:1,
			items:aplay
		},{
			label:{text:'活动费用'},
			dataField:"cost_type",
			editorType:'dxSelectBox',
			editorOptions:{
				dataSource:[{text:'免费',value:0}],
				displayExpr:'text',
				valueExpr:'value'
			}
		}]

		let form_type = {toll:[],type:[] }

			let content = function(details=[],selection=[],formdata=[]){
			
			page.content.find('.data-grid').html('')

			let  items =[{
			label:{text:"类型"},
			dataField:"toll",
			editorType:"dxRadioGroup",
			editorOptions:{
				displayExpr:'text',
				valueExpr:'value',
				layout: "horizontal",
				dataSource:[{
					text:'收费活动',
					value:1
				},{
					text:'免费活动',
					value:0
				}],
				onValueChanged:function(e){
					let value=Number(e.value);
					switch(value){
						case 1:form_type['toll']=item1;break;
						case 0:form_type['toll']=item2;
					};

					content(form_type.toll,form_type.type)
				}
			}
		},{
			label:{text:"类型"},
			dataField:"type",
			editorType:"dxRadioGroup",
			editorOptions:{
				displayExpr:'text',
				valueExpr:'value',
				  layout: "horizontal",
				dataSource:[{
					text:'文章',
					value:'article'
				},{
					text:'海报',
					value:'poster'
				}],
				onValueChanged:function(e){
					let value=e.value;
					switch(value){
						case 'article':form_type['type']=detail1;break;
						case 'poster':form_type['type']=detail2;
					};

					content(form_type.toll,form_type.type)
				}
			}
		},{
			label:{text:'活动名称'},
			dataField:'name'
		},{
			label:{text:'摘要'},
			dataField:"abstract"
		},{
			label:{text:'封面图片'},
			dataField:"covers",
			editorType:'imagesdetail',
			editorOptions:{
				imageWidth:400,
				imageHeight:200
			}
		},{
			itemType:"group",
			colCount:1,
			items:selection
		},{
			itemType:'group',
			colCount:1,
			items:details
		}]

		if(origin =='NEW'){
				page.content.find('.data-grid').dxForm({
				showColonAfterLabel: true,
            	showValidationSummary: false,
            	alignItemLabels: true,
            	alignItemLabelsInAllGroups: true,
            	items:items
				}).dxForm('instance').updateData('start_time',DATE)		
		}else{
			page.content.find('.data-grid').dxForm({
				formData:formdata,
				showColonAfterLabel: true,
            	showValidationSummary: false,
            	alignItemLabels: true,
            	alignItemLabelsInAllGroups: true,
            	items:items
				})
				
		}
				
			}

			let submit = {
				location:'after',
				widget:'dxButton',
				options:{
					text:'保存',
					type:'default',
					onClick:function(){
						let DATA = page.content.find('.data-grid').dxForm('instance').option('formData');

						DATA['product_ids']=DATA.products.join(',');
						DATA['state']='publish';
						console.log(DATA);
						$.ajax({
							url:$.config('apiUrl')+'restful?_model=activity',
							type:'post',
							data:DATA
						}).always(function(res){
							console.log(res)
								if(res.status=='success'){
									DevExpress.ui.notify('保存成功','success',1500);
									setTimeout(function(){
										window.history.go(-1)
									},1500)
								}else{
									DevExpress.ui.notify('保存失败：'+res.responseJSON.message,'warning',1500);
								}
						})
					}
				}
			}

			let goback = {
				location:'after',
				widget:'dxButton',
				options:{
					text:'返回',
					type:'normal',
					onClick:function(){
						window.history.go(-1)
					}
				}
			}

			let toolbar = []

			if(origin != 'NEW'){
				$.get($.config('apiUrl')+`restful/${origin}?_model=activity`).then(res =>{
				

			let det=res.data.type;
					switch(det){
						case 'article':form_type['type']=detail1;break;
						case 'poster':form_type['type']=detail2;
					};
			
			let toll=Number(res.data.toll);
					switch(toll){
						case 1:form_type['toll']=item1;break;
						case 0:form_type['toll']=item2;
					};

				content(form_type.toll,form_type.type,res.data);

				page.content.find('.data-grid').dxForm('instance').getEditor('start_time',res.data.start_time);
				page.content.find('.data-grid').dxForm('instance').getEditor('end_time',res.data.end_time)
			})

			toolbar.push(goback)

			}else{
				content() ;
			toolbar.push(submit,goback)
			}
			


		

		page.content.find('.toolbar1').dxToolbar({
			items:toolbar
		})	
	}
})